<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="6" :sm="12">
            <a-form-item label="客户名称">
              <j-input placeholder="请输入客户名称" v-model="queryParam.customerName" allowClear></j-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item label="客户编号">
              <a-input placeholder="请输入客户编号" v-model="queryParam.customerCode" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item label="客户类型">
              <j-dict-select-tag v-model="queryParam.customerType" placeholder="请选择客户类型" dictCode="customer_type" allowClear/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item label="联系人">
              <a-input placeholder="请输入联系人" v-model="queryParam.contactPerson" allowClear></a-input>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :md="6" :sm="8">
              <a-form-item label="所属行业">
                <j-dict-select-tag v-model="queryParam.industry" placeholder="请选择所属行业" dictCode="industry_type" allowClear/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item label="客户来源">
                <j-dict-select-tag v-model="queryParam.customerSource" placeholder="请选择客户来源" dictCode="customer_source" allowClear/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item label="信用等级">
                <j-dict-select-tag v-model="queryParam.creditRating" placeholder="请选择信用等级" dictCode="credit_rating" allowClear/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item label="跟进状态">
                <j-dict-select-tag v-model="queryParam.followUpStatus" placeholder="请选择跟进状态" dictCode="follow_up_status" allowClear/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item label="跟进人员">
                <a-input placeholder="请输入跟进人员" v-model="queryParam.followUpPerson" allowClear></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item label="单位名称">
                <a-input placeholder="请输入单位名称" v-model="queryParam.unitName" allowClear></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item label="客户标签">
                <a-input placeholder="请输入客户标签" v-model="queryParam.customerTag" allowClear></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item label="信用额度">
                <a-input-number style="width:45%" placeholder="最小值" v-model="queryParam.creditLimit_begin" allowClear></a-input-number>
                <span style="display: inline-block; text-align: center; width: 10%">-</span>
                <a-input-number style="width:45%" placeholder="最大值" v-model="queryParam.creditLimit_end" allowClear></a-input-number>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item label="账期天数">
                <a-input-number style="width:45%" placeholder="最小值" v-model="queryParam.paymentTerm_begin" allowClear></a-input-number>
                <span style="display: inline-block; text-align: center; width: 10%">-</span>
                <a-input-number style="width:45%" placeholder="最大值" v-model="queryParam.paymentTerm_end" allowClear></a-input-number>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item label="省份">
                <a-select 
                  v-model="queryParam.provinceCode" 
                  placeholder="请选择省份" 
                  @change="provinceChange" 
                  allowClear>
                  <a-select-option v-for="(name, code) in provinceOptions" :key="code" :value="code">
                    {{ name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item label="城市">
                <a-select 
                  v-model="queryParam.cityCode" 
                  placeholder="请选择城市" 
                  @change="cityChange" 
                  :disabled="!queryParam.provinceCode"
                  allowClear>
                  <a-select-option v-for="(name, code) in cityOptions" :key="code" :value="code">
                    {{ name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item label="区县">
                <a-select 
                  v-model="queryParam.areaCode" 
                  placeholder="请选择区县" 
                  :disabled="!queryParam.cityCode"
                  allowClear>
                  <a-select-option v-for="(name, code) in areaOptions" :key="code" :value="code">
                    {{ name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <a-col :md="6" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus" v-if="hasPermission('crm:customer:add')">新增客户</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('客户信息')" v-if="hasPermission('crm:customer:export')">导出</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel" v-if="hasPermission('crm:customer:delete')">
            <a-icon type="delete"/>
            删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作
          <a-icon type="down"/>
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i>已选择&nbsp;<a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项&nbsp;&nbsp;
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        bordered
        size="middle"
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        :scroll="{x: 'max-content'}"
        class="j-table-force-nowrap"
        @change="handleTableChange">
        
        <template slot="areaSlot" slot-scope="text, record">
          <span>
            {{ record.provinceName || '' }}
            {{ record.cityName ? '/' + record.cityName : '' }}
            {{ record.areaName ? '/' + record.areaName : '' }}
          </span>
        </template>
        
        <template slot="customerTypeSlot" slot-scope="text">
          <j-dict-label :value="text" dictCode="customer_type"/>
        </template>
        
        <template slot="industrySlot" slot-scope="text">
          <j-dict-label :value="text" dictCode="industry_type"/>
        </template>
        
        <template slot="customerSourceSlot" slot-scope="text">
          <j-dict-label :value="text" dictCode="customer_source"/>
        </template>
        
        <template slot="creditRatingSlot" slot-scope="text">
          <j-dict-label :value="text" dictCode="credit_rating"/>
        </template>
        
        <template slot="followUpStatusSlot" slot-scope="text">
          <j-dict-label :value="text" dictCode="follow_up_status"/>
        </template>
        
        <template slot="resultSlot" slot-scope="text">
          <a-tag :color="text ? 'green' : 'red'">{{ text ? '有权限' : '无权限' }}</a-tag>
        </template>
        
        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)" v-if="hasPermission('crm:customer:edit')">编辑</a>
          <a-divider type="vertical" v-if="hasPermission('crm:customer:edit')"/>
          <a-dropdown>
            <a class="ant-dropdown-link">
              更多 <a-icon type="down"/>
            </a>
            <a-menu slot="overlay">
              <a-menu-item v-if="hasPermission('crm:customer:detail')">
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item v-if="hasPermission('project:add')">
                <a @click="handleAddProject(record)">添加工程</a>
              </a-menu-item>
              <a-menu-item v-if="hasPermission('crm:customer:delete')">
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <customer-modal ref="modalForm" @ok="modalFormOk"></customer-modal>
    <project-modal ref="projectModal" @ok="modalFormOk"></project-modal>
    <customer-detail-modal ref="detailModal"></customer-detail-modal>
  </a-card>
</template>

<script>
  import '@/assets/less/TableExpand.less'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import CustomerModal from './modules/CustomerModal.vue'
  import ProjectModal from './modules/ProjectModal.vue'
  import CustomerDetailModal from './modules/CustomerDetailModal.vue'
  import JDictSelectTag from '@/components/dict/JDictSelectTag'
  import JAreaLinkage from '@/components/jeecg/JAreaLinkage'
  import JInput from '@/components/jeecg/JInput'
  import { customerList, customerDelete, customerDeleteBatch, customerExport, customerImport } from '@/api/crm'

  export default {
    name: "CustomerList",
    mixins: [JeecgListMixin],
    components: {
      CustomerModal,
      ProjectModal,
      CustomerDetailModal,
      JDictSelectTag,
      JAreaLinkage,
      JInput
    },
    created() {
      this.loadProvinceData();
      
      // 加载权限数据
      this.loadPermissionData();
      
      // 页面加载时重置查询条件
      this.searchReset();
    },
    data() {
      return {
        description: '客户管理页面',
        // 查询条件
        queryParam: {},
        // 省市区数据
        provinceOptions: {},
        cityOptions: {},
        areaOptions: {},
        // 权限数据
        permissionList: [],
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title: '客户名称',
            align:"center",
            dataIndex: 'customerName',
            width: 150,
            ellipsis: true
          },
          {
            title: '客户编号',
            align: "center",
            dataIndex: 'customerCode',
            width: 120
          },
          {
            title: '客户类型',
            align:"center",
            dataIndex: 'customerType',
            width: 100,
            scopedSlots: { customRender: 'customerTypeSlot' }
          },
          {
            title: '所属行业',
            align:"center",
            dataIndex: 'industry',
            width: 100,
            scopedSlots: { customRender: 'industrySlot' }
          },
          {
            title: '客户来源',
            align:"center",
            dataIndex: 'customerSource',
            width: 100,
            scopedSlots: { customRender: 'customerSourceSlot' }
          },
          {
            title: '信用等级',
            align:"center",
            dataIndex: 'creditRating',
            width: 100,
            scopedSlots: { customRender: 'creditRatingSlot' }
          },
          {
            title: '跟进状态',
            align:"center",
            dataIndex: 'followUpStatus',
            width: 100,
            scopedSlots: { customRender: 'followUpStatusSlot' }
          },
          {
            title: '联系人',
            align:"center",
            dataIndex: 'contactPerson',
            width: 100
          },
          {
            title: '联系电话',
            align:"center",
            dataIndex: 'contactPhone',
            width: 120
          },
          {
            title: '信用额度',
            align:"center",
            dataIndex: 'creditLimit',
            width: 120,
            sorter: true,
            customRender: (text) => {
              if (!text && text !== 0) return '-';
              return text.toLocaleString('zh-CN', { style: 'currency', currency: 'CNY', minimumFractionDigits: 2 });
            }
          },
          {
            title: '账期天数',
            align:"center",
            dataIndex: 'paymentTerm',
            width: 100,
            sorter: true
          },
          {
            title: '地区',
            align: "center",
            dataIndex: 'area',
            width: 200,
            scopedSlots: { customRender: 'areaSlot' }
          },
          {
            title: '详细地址',
            align:"center",
            dataIndex: 'address',
            width: 200,
            ellipsis: true
          },
          {
            title: '电子邮箱',
            align:"center",
            dataIndex: 'email',
            width: 150
          },
          {
            title: '创建时间',
            align:"center",
            dataIndex: 'createTime',
            width: 150,
            sorter: true
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed: 'right',
            width: 150,
            scopedSlots: { customRender: 'action' }
          }
        ],
        // 请求地址
        url: {
          list: "/crm/customer/list",
          delete: "/crm/customer/delete",
          deleteBatch: "/crm/customer/deleteBatch",
          exportXlsUrl: customerExport
        },
        importUrl: customerImport
      }
    },
    methods: {
      loadData(arg) {
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        const params = this.getQueryParams();
        console.log('执行查询，参数:', params);
        this.loading = true;
        customerList(params).then((res) => {
          if (res.success) {
            this.dataSource = res.result.records || res.result;
            this.ipagination.total = res.result.total || 0;
          } else {
            this.$message.warning(res.message);
          }
        }).finally(() => {
          this.loading = false;
        });
      },
      searchReset() {
        this.queryParam = {};
        this.loadData(1);
      },
      searchQuery() {
        console.log('执行查询，参数:', this.queryParam);
        this.loadData(1);
      },
      handleDelete(id) {
        customerDelete({ id: id }).then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.loadData();
          } else {
            this.$message.warning(res.message);
          }
        });
      },
      batchDel() {
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning('请选择至少一条记录');
          return;
        }
        let ids = this.selectedRowKeys.join(',');
        let that = this;
        this.$confirm({
          title: "确认删除",
          content: "是否删除选中数据?",
          onOk: function () {
            that.loading = true;
            customerDeleteBatch({ ids: ids }).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.loadData();
                that.onClearSelected();
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.loading = false;
            });
          }
        });
      },
      handleDetail(record) {
        this.$refs.detailModal.show(record);
      },
      handleAddProject(record) {
        // 将客户数据传递给项目弹窗
        const projectData = {
          status: '0',
          customerId: record.id,
          customerName: record.customerName,
          contactPerson: record.contactPerson,
          contactPhone: record.contactPhone,
          provinceCode: record.provinceCode,
          cityCode: record.cityCode,
          areaCode: record.areaCode,
          provinceName: record.provinceName,
          cityName: record.cityName,
          areaName: record.areaName,
          address: record.address
        };
        
        this.$refs.projectModal.add(projectData);
        this.$refs.projectModal.title = "添加工程";
      },
      provinceChange(value) {
        this.queryParam.cityCode = undefined;
        this.queryParam.areaCode = undefined;
        this.areaOptions = {};
        if (value) {
          this.loadCityData(value);
        } else {
          this.cityOptions = {};
        }
      },
      cityChange(value) {
        this.queryParam.areaCode = undefined;
        if (value) {
          this.loadAreaData(value);
        } else {
          this.areaOptions = {};
        }
      },
      loadProvinceData() {
        this.provinceOptions = this.$Jpcaa['86'];
      },
      loadCityData(provinceCode) {
        this.cityOptions = this.$Jpcaa[provinceCode] || {};
      },
      loadAreaData(cityCode) {
        this.areaOptions = this.$Jpcaa[cityCode] || {};
      },
      // 加载权限数据
      loadPermissionData() {
        // 获取用户权限列表
        const userAuth = JSON.parse(sessionStorage.getItem('LOGIN_USER_BUTTON_AUTH') || '[]');
        const sysAuth = JSON.parse(sessionStorage.getItem('SYS_BUTTON_AUTH') || '[]');
        
        // 合并权限数据
        this.permissionList = [];
        
        // 处理用户权限
        userAuth.forEach(auth => {
          if (typeof auth === 'string') {
            this.permissionList.push(auth);
          } else if (auth && auth.action) {
            this.permissionList.push(auth.action);
          }
        });
        
        // 处理系统权限
        sysAuth.forEach(auth => {
          if (typeof auth === 'string') {
            if (!this.permissionList.includes(auth)) {
              this.permissionList.push(auth);
            }
          } else if (auth && auth.action) {
            if (!this.permissionList.includes(auth.action)) {
              this.permissionList.push(auth.action);
            }
          }
        });
      },
      
      // 判断是否有权限
      hasPermission(permission) {
        if (!permission) return false;
        
        // 检查权限列表中是否包含指定权限
        if (this.permissionList.includes(permission)) {
          return true;
        }
        
        // 检查权限列表中是否包含以逗号分隔的多个权限
        for (let perm of this.permissionList) {
          if (perm && perm.includes(',')) {
            const perms = perm.split(',');
            if (perms.includes(permission)) {
              return true;
            }
          }
        }
        
        return false;
      }
    }
  }
</script>

<style scoped>
  .ant-card-body .table-operator {
    margin-bottom: 18px;
  }
  .ant-table-tbody .ant-table-row td {
    padding-top: 15px;
    padding-bottom: 15px;
  }
  .anty-row-operator button {
    margin: 0 5px
  }
  .ant-btn-danger {
    background-color: #ffffff
  }
  .ant-modal-cust-warp {
    height: 100%
  }
  .ant-modal-cust-warp .ant-modal-body {
    height: calc(100% - 110px) !important;
    overflow-y: auto
  }
  .ant-modal-cust-warp .ant-modal-content {
    height: 90% !important;
    overflow-y: hidden
  }
  
  /* 表格横向滚动样式 */
  .ant-table-wrapper {
    overflow-x: auto;
  }
  .ant-table-body {
    overflow-x: auto !important;
  }
  /* 适配小屏幕设备 */
  @media screen and (max-width: 1200px) {
    .ant-table-content {
      overflow-x: auto;
    }
  }
  
  /* 固定列样式 */
  .ant-table-fixed-right {
    box-shadow: -6px 0 6px -4px rgba(0, 0, 0, 0.15);
  }
  
  .ant-table-tbody > tr > td.ant-table-fixed-columns-in-body {
    background-color: #fff;
  }

  /* 查询区域样式优化 */
  .table-page-search-wrapper {
    margin-bottom: 18px;
    background-color: #fff;
    padding: 16px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  }
  
  .table-page-search-submitButtons {
    display: flex;
    align-items: center;
    margin-top: 24px;
  }
</style> 